import '@/App.scss';
import MyHead from './component/MyHeader';
import useMyRoutes from './hook/useMyRoutes';
import { Suspense, useEffect } from 'react';
import { FloatButton } from 'antd';
import { userLogin } from './request';
import userStore from './store/userStore';
import { requestSourceMap } from './request/myAxios';
import Loading from './component/Loading';

let prePathname: string;

function App() {
  //初始化路由、登录
  const routes = useMyRoutes();

  const changeRoute = (r: typeof routes) => {
    if (!r) return;
    init();
    for (const [, source] of requestSourceMap) {
      source.cancel();
    }
    requestSourceMap.clear();

    const pathname: string = r.props.match.pathname;
    if (prePathname !== pathname) document.documentElement.scrollTop = 0;
    prePathname = pathname;
    if (pathname === '/home') return r;
    return <div className='content-container'>{r}</div>;
  };

  useEffect(() => {
    init();
  }, []);

  const init = async () => {
    try {
      if (userStore.isLogin) return;
      const token = localStorage.getItem('token');
      if (!token) throw new Error('没有token');
      const user = await userLogin();
      userStore.login(user);
    } catch (error) {
      userStore.logout();
    }
  };

  return (
    <div className={`App`}>
      <MyHead></MyHead>
      <Suspense fallback={<Loading>页面加载中...</Loading>}>
        {changeRoute(routes)}
      </Suspense>
      <FloatButton.BackTop style={{ bottom: 20, right: 70 }} />
    </div>
  );
}

export default App;
